package com.fyt.ZhongYaoApp.service.impl;

import com.fyt.ZhongYaoApp.mapper.CollectionMapper;
import com.fyt.ZhongYaoApp.pojo.Collection;
import com.fyt.ZhongYaoApp.pojo.Result;
import com.fyt.ZhongYaoApp.pojo.User;
import com.fyt.ZhongYaoApp.pojo.vo.EssayCollectionVO;
import com.fyt.ZhongYaoApp.pojo.vo.ZYCollectionVO;
import com.fyt.ZhongYaoApp.service.CollectionService;
import com.fyt.ZhongYaoApp.service.UserService;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CollectionServiceImpl implements CollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private UserService userService;

    /**
     * 添加文章收藏 / 中药收藏
     *
     * @param collection
     * @return
     */
    @Override
    public Boolean addCollection(Collection collection) {
        /**
         * 封装用户信息
         */
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        collection.setUserId(userId);

        LocalDateTime now = LocalDateTime.now();
        collection.setCreateTime(now);

        // 判断文章是否存在


        // 判断是否已经收藏文章
        Collection collection1 = collectionMapper.findEssayif(collection);
        System.out.println(collection1);
        if(collection1!=null){// 已经收藏过了该文章
            collectionMapper.cancelCollection(collection);// 删除之前的收藏
            return false;
        }else {// 还没有收藏该文章
            collectionMapper.addCollection(collection);// 添加收藏
            return true;
        }
    }

    @Override
    public List<EssayCollectionVO> essayList() {
        // 得到用户id
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        // 查询列表
        List<EssayCollectionVO> list = collectionMapper.essayList(userId);
        return list;
    }

    @Override
    public List<ZYCollectionVO> zyList() {
        // 得到用户id
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        System.out.println("用户id：" + userId);
        // 查询列表
        List<ZYCollectionVO> list = collectionMapper.zyList(userId);
        return list;
    }
}
